//
//  JBAPIManager.swift
//  joyBao
//
//  Created by Chen on 2017/7/29.
//  Copyright © 2017年 Chen. All rights reserved.
//

import UIKit
import Alamofire
import HandyJSON

class JBAPIManager: NSObject {

    class func beforeRequestParameters(type: RequestType,
                                 URLString: String,
                                 parameters: [String: Any]? = nil) ->
        (method: HTTPMethod, params: [String: Any], URLString: String, header: HTTPHeaders) {
            var parameters = parameters == nil ? [:] : parameters!
            let URLString = serverHostUrl + URLString
            let method = type == .get ? HTTPMethod.get : HTTPMethod.post
            var header = HTTPHeaders()

//            if let token = JBUserInfoManager.shared.token {//接口带上token
                if type == .get {
                    parameters.updateValue("avKC7LIkiRojFQcN6HAiuNsQZINkJaRMkEbAbuwPuKi", forKey: "access_token")
                } else if type == .post {
//                    header["authorization"] = "Bearer \(token)"
                    header["authorization"] = "Bearer avKC7LIkiRojFQcN6HAiuNsQZINkJaRMkEbAbuwPuKi"
                }
//            }

            return (method, parameters, URLString, header)
    }

    /// 带对象封装的网络请求
    ///
    /// - Parameters:
    ///   - type: 请求类型
    ///   - URLString: 请求地址
    ///   - parameters: 参数
    ///   - modelType: 需封装的对象
    ///   - successCallback: 成功的回调
    ///   - failedCallback: 失败的回调
    class func requestData<T: HandyJSON>(_ type: RequestType,
                           URLString: String,
                           parameters: [String: Any]? = nil,
                           modelType: T.Type = T.self,
                           successCallback: @escaping (_ result: Any) -> (),
                           failedCallback: @escaping (_ error: String) -> ()) {

        if !UserDefaults.standard.bool(forKey: kNetworkReachableKey) {
            failedCallback("请检查网络连接")
            return
        }

        let (method, parameters, URLString, header) = self.beforeRequestParameters(type: type, URLString: URLString, parameters: parameters)

        Alamofire.request(URLString, method: method, parameters: parameters, encoding: URLEncoding.default, headers: header).responseJSON { (response) in

            guard let result = response.result.value else {
                BBLog(message: response.result.error!)
                failedCallback(response.result.error!.localizedDescription)
                return
            }

            let requestResult = JBRequestResult.deserialize(from: result as? NSDictionary)!

            if !requestResult.success! {//请求失败
                failedCallback(requestResult.message == nil ? "请求失败" : requestResult.message!)
                return
            }

            if requestResult.data == nil {//data为空
                successCallback(result)
            } else {//json转model，将结果回调回去
                successCallback(BaseModel.dictToModel(modelType, dict: requestResult.data)!)
            }
        }
    }


    /// 不封装对象的网络请求
    ///
    /// - Parameters:
    ///   - type: 请求类型
    ///   - URLString: url地址
    ///   - parameters: 参数
    ///   - successCallback: 请求成功回调
    ///   - failedCallback: 请求失败回调
    class func requestData(_ type: RequestType,
                           URLString: String,
                           parameters: [String: Any]? = nil,
                           successCallback: @escaping (_ result: Any) -> (),
                           failedCallback: @escaping (_ error: String) -> ()) {

        if !UserDefaults.standard.bool(forKey: kNetworkReachableKey) {
            failedCallback("请检查网络连接")
            return
        }

        let (method, parameters, URLString, header) = self.beforeRequestParameters(type: type, URLString: URLString, parameters: parameters)

        Alamofire.request(URLString, method: method, parameters: parameters, encoding: URLEncoding.default, headers: header).responseJSON { (response) in

            guard let result = response.result.value else {
                BBLog(message: response.result.error!)
                failedCallback(response.result.error!.localizedDescription)
                return
            }

            let requestResult = JBRequestResult.deserialize(from: result as? NSDictionary)!

            if !requestResult.success! {//请求失败
                failedCallback(requestResult.message == nil ? "请求失败" : requestResult.message!)
                return
            }

            if requestResult.data == nil {//data为空
                successCallback(result)
            } else {//将结果回调回去
                successCallback(requestResult.data!)
            }
        }
    }

}
